<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class System extends Backend_Controller {

	/**
	 * 构造函数
	 */
	public function __construct() {
		parent::__construct();
		$this->isValidRequest();
		//加载admin模型
		$this->load->model('backend/System_model', 'System');
		//加载验证类
		$this->load->library('form_validation');
	}
	
	/**
	 * 首页
	 */
	public function index()
	{
		$result = $this->System->findSystemInfo();
		$this->load->view('backend/system/index', $result);
	}
	public function add() {
		$this->form_validation->validateData(array(
			'name','value','cfgname', 'type', 'parent'
		), array(
			array('name', 'required'),
			array('type', 'required'),
			array('cfgname', 'required'),
			array('parent', 'required|integer'),
		));
		if($this->form_validation->hasErrors()) {
			$this->renderJson(300, $this->form_validation->error);
		}
		$data = $this->form_validation->attributes;
		$result = $this->System->insert($data);
		if($result) {
			$this->mkConfig();
			$this->renderJson(200, '', array(
				'navTabId' => 'backendsystemindex'
			));
		}
		$this->renderJson(300);
	}
	/**
	 * 修改系统信息
	 */
	public function edit() {
		$post = $this->input->post();
		$data = array();
		foreach ($post as $k=>$v) {
			$data[] = array('cfgname'=>$k,'value'=>$v);
		}
		$result = $this->System->upSystemInfo($data, 'cfgname');
		if($result) {
			$this->mkConfig();
			$this->renderJson(200, '', array(
				'navTabId' => 'backendsystemindex'
			));
		}
		$this->renderJson(300);
	}
	private function mkConfig() {
		$result = $this->System->get_result(array('parent !=' => '0'));
		if(!empty($result)) {
			$string = "<?php \n";
			foreach ($result as $v) {
				$string .= "\$config['{$v['cfgname']}'] = '{$v['value']}';\n";
			}
			file_put_contents(APPPATH . '/config/system_info.php', $string);
		}
	}
}
